package com.liuzhao.packet.server;

import com.liuzhao.packet.core.HelloHandler;
import com.liuzhao.packet.core.MyDecoder;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * netty服务端入门
 *
 * @author liuxianzhao
 */
public class NettyServerStartup {

    private static int serverPort = 10101;  //服务端口

    private ExecutorService boss = null;    //boss线程监听端口

    private ExecutorService worker = null;  //worker线程负责数据读写


    public void start() {
        //服务类
        ServerBootstrap bootstrap = new ServerBootstrap();

        //boss线程监听端口，worker线程负责数据读写
        boss = Executors.newCachedThreadPool();
        worker = Executors.newCachedThreadPool();

        //设置niosocket工厂
        bootstrap.setFactory(new NioServerSocketChannelFactory(boss, worker));

        //设置管道的工厂
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

            public ChannelPipeline getPipeline() throws Exception {

                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("decoder", new MyDecoder());
                pipeline.addLast("handler1", new HelloHandler());
                return pipeline;
            }
        });

        bootstrap.bind(new InetSocketAddress(serverPort));

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                worker.shutdown();
                boss.shutdown();
            }
        });

    }


    private static class Singleton {
        private static NettyServerStartup singleton = new NettyServerStartup();
    }

    public static NettyServerStartup newInstance() {
        return Singleton.singleton;
    }

    public static void setServerPort(int serverPort) {
        NettyServerStartup.serverPort = serverPort;
    }

}
